
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
import {generateUniqueString} from "@/utils/passwordUtil";
const db = cloud.database()
const _ = db.command

/**
 * 角色新增
 * @param ctx
 */
export default async function (ctx: FunctionContext) {
  /**
   * {
   *   "roleName": "超级管理员"
   * }
   */
  let body = ctx.body
  if (nw.util.isNull(body.roleName)){
    return fail("角色名不能为空")
  }
  //校验角色名是否重复
  let count = await nw.db.count({
    dbName:"role",
    whereJson:{
      roleName:_.eq(body.roleName),
      deleted:0
    }
  })
  if (count>0){
    return fail("角色名重复")
  }

  //生成唯一六位字符串函数
  let roleCode = await genCode()
  let role = {
    roleName:body.roleName,
    roleCode:roleCode,
    remark:"",
    createTime:new Date(),
    updateTime:new Date(),
    deleted:0
  }
  //保存角色信息
  let res = await nw.db.add({
    dbName:"role",
    dataJson:role
  })
  if (nw.util.isNull(res)){
    console.log(res)
    return fail("新增角色信息失败")
  }

  return ok("新增成功")



}

async function genCode() {
  let code = ""
  while (true){
    code = generateUniqueString(6)
    let count = await nw.db.count({
      dbName:"role",
      whereJson:{
        roleCode:_.eq(code),
        deleted:0
      }
    })
    if (count===0){
      break
    }
  }
  return code
}
